#include "Factorization.h"


Factorization::Factorization(void)
{
}


Factorization::~Factorization(void)
{
}

void initRandomMatrix(MatrixObject& m)
{
	for(int i = 0; i < m.ROWS; i++)
	{
		for(int j = 0; j < 1; j++)
		{
			//double temp =0.01*(int)(rand()%100);
			//double temp=i*j/double(m.ROWS*m.COLS);
			//double temp=1;
			double temp=0.45+(int)(rand()%6)/60.0;

			//cout<<temp<<endl;
			m.setElement(i,j,temp);
		}
	}
}

void check1(MatrixObject& m)
{
	for(int i = 0; i < m.ROWS; i++)
	{
		for(int j = 0; j < m.COLS; j++)
		{
			if(m.getElement(i,j) >1) m.setElement(i,j,1);
		}
	}
}

//static	SparseMatrix X1(0,0);//=X.matricification(1);
//static	SparseMatrix X2(0,0);//=X.matricification(2);
//static	SparseMatrix X3(0,0);//=X.matricification(3);
	


void Factorization::NTF(Tensor X,MatrixObject& F,MatrixObject& G,MatrixObject& H,int times)
{
	initRandomMatrix(F);
	initRandomMatrix(G);
	initRandomMatrix(H);
	//F.Output();
	//G.Output();
	//H.Output();
	SparseMatrix X1=X.matricification(1);
	SparseMatrix X2=X.matricification(2);
	SparseMatrix X3=X.matricification(3);

	MatrixObject temp1(X1.ROWS,F.COLS);
	SparseMatrix temp2(0,0);
	MatrixObject temp3(X1.ROWS,F.COLS);

	

	cout<<"Finish\n";

for(int count = 0; count < times; count++)
{
	temp1 = X1.s_n(G,H);
	X1.WeightedElementwiseProduct(F,G,H,temp2);
	temp3 = temp2.s_n(G,H);
	F=F.elementwiseProduct(temp1).elementwiseDivision(temp3);
	check1(F);
	cout<<"On the "<<count<<" Iteration F = ";
	//F.Output();
	cout<<"\n";
	
	//system("pause");

    temp1 = X2.s_n(H,F);
	X2.WeightedElementwiseProduct(G,H,F,temp2);
     temp3 = temp2.s_n(H,F);
	G=G.elementwiseProduct(temp1).elementwiseDivision(temp3);
	check1(G);
	cout<<"On the "<<count<<" Iteration G = ";
//	G.Output();
	cout<<"\n";

	temp1 = X3.s_n(F,G);
	 X3.WeightedElementwiseProduct(H,F,G,temp2);
    temp3 = temp2.s_n(F,G);

	H=H.elementwiseProduct(temp1).elementwiseDivision(temp3);
	check1(H);
	cout<<"On the "<<count<<" Iteration H = ";
//	H.Output();
	cout<<"\n";

	//system("pause");
	}

}